package net.base;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author: jiangxiangwei
 * @date: 2009-12-18
 */
public class Tools {
	/**
	 * 将map转为json串
	 * 
	 * @param map
	 * @return
	 */
	public static String toJsonByMap(Map map) {
		if (map == null || map.size() == 0)
			return "\"\",";
		StringBuffer sb = new StringBuffer("{");
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Object key = entry.getKey();
			Object value = entry.getValue();
			sb.append("\"").append(key).append("\":").append("\"").append(
					nullToString(value)).append("\",");
		}
		int len = sb.length();
		sb.delete(len - 1, len);
		sb.append("},");
		return sb.toString();
	}

	/**
	 * 将map转为json串，list转json时使用
	 * 
	 * @param map
	 * @return
	 */
	public static String toJsonByMap2(Map map) {
		if (map == null || map.size() == 0)
			return "{},";
		StringBuffer sb = new StringBuffer("{");
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Object key = entry.getKey();
			Object value = entry.getValue();
			sb.append("\"").append(key).append("\":").append("\"").append(
					nullToString(value)).append("\",");
		}
		int len = sb.length();
		sb.delete(len - 1, len);
		sb.append("},");
		return sb.toString();
	}

	/**
	 * 将list转为json串
	 * 
	 * @param list
	 * @return
	 */
	public static String toJsonByList(List list) {
		if (list == null || list.size() == 0)
			return "[],";
		StringBuffer sb = new StringBuffer("[");
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Map map = (Map) it.next();

			sb.append(toJsonByMap2(map));
		}
		int len = sb.length();
		sb.delete(len - 1, len);
		sb.append("],");
		return sb.toString();
	}

	public static Object nullToString(Object str) {
		if (str == null || "null".equals(str))
			return "";
		else
			return string2Json(String.valueOf(str));
	}

	/**
	 * 将 String 对象编码为 JSON 格式时，只需处理好特殊字符即可。另外，必须用 (") 而非 (') 表示字符串
	 * 
	 * @param s
	 *            需要转化的字符串
	 * @return 返回转化好的字符串
	 */
	public static String string2Json(String s) {
		StringBuffer sb = new StringBuffer(s.length() + 20);
		// sb.append('\"');
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '\"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '/':
				sb.append("\\/");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			default:
				sb.append(c);
			}
		}
		// sb.append('\"');
		return sb.toString();
	}
    public static Map parserRequest(HttpServletRequest request) {
        Map map = new HashMap();
        Enumeration enume = request.getParameterNames();
        while (enume.hasMoreElements()) {
            String pName = (String) enume.nextElement();
            String value = request.getParameter(pName);
            if (value != null && !value.equals(""))
                map.put(pName, convert(request.getParameter(pName)));
            value = null;
        }
        return map;
    }

    public static Map parserString(String str) {
        Map map = new HashMap();
        String[] str1 = str.split("&");
        for (int i = 0; i < str1.length; i++) {
            String[] str2 = str1[i].split("=");
            //System.out.println("数组长度" + str2.length);
            if (str2.length == 1) {
                map.put(str2[0], "");
            } else {
                map.put(str2[0], str2[1]);
            }
        }
        return map;
    }

    /* 字符串编码转换为UTF-8
    *
            * @param str 被处理的字符串
    * @return String 将数据库中读出的数据进行转换
    */
    public static String convert(String str) {
        String str1 = "";
        if (str != null) {
            try {
                str1 = new String(str.getBytes("ISO8859_1"), "UTF-8");
            } catch (Exception e) {
                str1 = "";
            }
        }
        return str1;
    }

    /**
     * 字符串编码反转换为ISO8859_1
     *
     * @param str 被处理的字符串
     * @return String 将jsp提交的数据进行转换放入数据库中
     */
    public static String reconvert(String str) {
        String str1 = null;
        if (str != null) {
            try {
                str1 = new String(str.getBytes("UTF-8"), "ISO8859_1");
            } catch (Exception e) {
                return str1;
            }
        }
        return str1;
    }

}
